<template>
  <el-card>
    <!-- 卡片头部 -->
    <div slot="header" class="clearfix">
      <span style="font-size: 18px;">保养</span>
    </div>

    <!-- 查询区域 -->
    <el-row :gutter="20" style="margin-bottom: 15px;">
      <el-col :span="3">
        <el-select v-model="searchConfig.lineId" placeholder="请选择产线" clearable width="100%">
          <el-option v-for="line in lineOptions" :key="line.line_id" :label="line.line_name"
            :value="line.line_id"></el-option>
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-input v-model="searchConfig.machineNumber" placeholder="请输入贴片机编号" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-input v-model="searchConfig.headNumber" placeholder="请输入贴装头编号" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </el-col>


      <el-col :span="1" style="text-align: right;">
        <el-button type="primary" @click="handleSearch">
          <i class="fa fa-refresh"></i> 查询
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table :data="configList" border stripe style="width: 100%;"
      :header-cell-style="{ background: '#f5f7fa', color: '#333' }" @row-dblclick="handleRowDblClick">

      <el-table-column prop="lineNumber" label="线别" align="center" min-width="80"></el-table-column>
      <el-table-column prop="maintenanceDate" label="保养日期" align="center" min-width="120"></el-table-column>
      <el-table-column prop="machineNumber" label="贴片机编号" align="center" min-width="120"></el-table-column>
      <el-table-column prop="machineHead" label="机头" align="center" min-width="80"></el-table-column>
      <el-table-column prop="headNumber" label="贴装头编号" align="center" min-width="120"></el-table-column>
      <el-table-column prop="headCount" label="头数" align="center" min-width="80"></el-table-column>
      <el-table-column prop="maintenanceFrequency" label="保养频度(天)" align="center" min-width="100"></el-table-column>
      <el-table-column prop="warningDays" label="保养预警(天)" align="center" min-width="100"></el-table-column>
      <el-table-column prop="useDay" label="当前使用天数" align="center" min-width="110">
      </el-table-column>
      <el-table-column prop="count" label="保养累计(数)" align="center" min-width="110">
      </el-table-column>
      <el-table-column prop="maintenanceItem" label="保养项目" align="center" min-width="100"></el-table-column>
      <el-table-column prop="maintenanceResult" label="保养结果" align="center" min-width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.maintenanceResult === 'OK' ? 'success' : 'danger'">
            {{ scope.row.maintenanceResult }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="implementer" label="实施担当" align="center" min-width="100"></el-table-column>
      <el-table-column prop="abnormalDescription" label="项目异常描述" align="center" min-width="200">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.abnormalDescription" placement="top">
            <div class="text-ellipsis" style="width: 100%">{{ scope.row.abnormalDescription }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div style="margin-top: 15px; text-align: right;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
      </el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="configForm" label-width="120px" style="margin-top: 20px;">
        <!-- 线别 -->
        <el-form-item label="线别" prop="lineNumber">
          <el-select v-model="form.line" placeholder="请选择产线" clearable width="100%" disabled>
            <el-option v-for="line in lineOptions" :key="line.line_id" :label="line.line_name"
              :value="line.line_id"></el-option>
          </el-select>
        </el-form-item>

        <!-- 贴片机编号 -->
        <el-form-item label="贴片机编号" prop="machineNumber">
          <el-input v-model="form.machineNumber" placeholder="请输入贴片机编号" clearable disabled></el-input>
        </el-form-item>

        <!-- 面数 -->
        <el-form-item label="面数" prop="side">
          <el-input v-model="form.machineHead" placeholder="" clearable disabled></el-input>
        </el-form-item>

        <!-- 保养日期 - 编辑时显示，新增时可自动生成或手动输入 -->
        <el-form-item label="保养日期" prop="maintenanceDate">
          <el-date-picker v-model="form.maintenanceDate" type="date" placeholder="选择保养日期" style="width: 100%;" 
            value-format="yyyy-MM-dd" disabled>
          </el-date-picker>
        </el-form-item>

        <!-- 机头 -->
        <el-form-item label="机头" prop="machineHead">
          <el-input v-model="form.machineHead" placeholder="请输入机头" clearable disabled></el-input>
        </el-form-item>

        <!-- 贴装头编号 -->
        <el-form-item label="贴装头编号" prop="headNumber">
          <el-input v-model="form.headNumber" placeholder="请输入贴装头编号" clearable disabled></el-input>
        </el-form-item>

        <!-- 头数 -->
        <el-form-item label="头数" prop="headCount">
          <el-input v-model="form.headCount" placeholder="请输入头数" type="number" clearable></el-input>
        </el-form-item>

        <!-- 保养频度 -->
        <el-form-item label="保养频度(天)" prop="maintenanceFrequency">
          <el-input v-model="form.maintenanceFrequency" placeholder="请输入保养频度（正整数）" type="number" min="1"
            disabled></el-input>
        </el-form-item>

        <!-- 保养预警 -->
        <el-form-item label="保养预警(天)" prop="warningDays">
          <el-input v-model="form.warningDays" placeholder="请输入保养预警天数（正整数）" type="number" min="1" disabled></el-input>
        </el-form-item>

        <!-- 当前使用 天数 -->
        <el-form-item label=" 当前使用 天数" prop="maintenanceFrequency">
          <el-input v-model="form.useDay" placeholder="" type="number" min="1" disabled></el-input>
        </el-form-item>

        <!-- 累计保养数 -->
        <el-form-item label="累计保养数" prop="warningDays">
          <el-input v-model="form.count" placeholder="" type="number" min="1" disabled></el-input>
        </el-form-item>

        <!-- 保养项目 -->
        <el-form-item label="保养项目" prop="maintenanceItem">
          <el-input v-model="form.maintenanceItem" placeholder="请输入保养项目" clearable></el-input>
        </el-form-item>

        <!-- 保养结果 -->
        <el-form-item label="保养结果" prop="maintenanceResult">
          <el-radio-group v-model="form.maintenanceResult">
            <el-radio label="OK">OK</el-radio>
            <el-radio label="NG">NG</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 实施担当 -->
        <el-form-item label="实施担当" prop="implementer">
          <el-input v-model="form.implementer" placeholder="请输入实施担当" clearable></el-input>
        </el-form-item>

        <!-- 项目异常描述 -->
        <el-form-item label="项目异常描述" prop="abnormalDescription">
          <el-input v-model="form.abnormalDescription" placeholder="请输入项目异常描述（可选）" type="textarea" rows="3"></el-input>
        </el-form-item>

      
      </el-form>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认保存</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>

import { lineList } from "@/api/qcsystem/qcdata"
import { maintenanceDLBySearch,addMaintenanceLogdata } from "@/api/maintenance/logData"
import r from "highlight.js/lib/languages/r";
export default {
  name: 'MaintenanceConfig',
  data() {
    return {
      // 配置列表数据源
      configList: [
      ],
      // 查询条件
      searchConfig: {
        lineId: '',
        machineNumber: '',
        headNumber: ''
      },
      lineOptions: [],
      totalCount: 0,
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增配置', // 弹窗标题（新增/编辑切换）
      // 表单数据
      form: {
        line: '',
        side: '',
        machineNumber: '',
        machineHead: '',
        headNumber: '',
        maintenanceFrequency: '',
        warningDays: ''
      },
      // 表单验证规则
      rules: {
        line: [
          { required: true, message: '请选择面数', trigger: 'change' },
        ],
        side: [
          { required: true, message: '请选择面数', trigger: 'change' }
        ],
        machineNumber: [
          { required: true, message: '请输入贴片机编号', trigger: 'blur' },
          { min: 5, max: 30, message: '贴片机编号长度需在5-30字符之间', trigger: 'blur' }
        ],
        machineHead: [
          { required: true, message: '请输入机头', trigger: 'blur' },
        ],
        headNumber: [
          { required: true, message: '请输入贴装头编号', trigger: 'blur' },
        ],
        maintenanceFrequency: [
          { required: true, message: '请输入保养频度', trigger: 'blur' },
        ],
        warningDays: [
          { required: true, message: '请输入保养预警天数', trigger: 'blur' },
        ]
      }
    };
  },
  created() {
    this.getLine()
  },
  computed: {

  },
  methods: {
    //查询产线
    getLine() {
      lineList().then(response => {
        this.lineOptions = response
      })
    },
    // 重置查询条件
    resetSearch() {
      this.searchConfig = {
        lineNumber: '',
        machineNumber: '',
        headNumber: ''
      };
      this.currentPage = 1; // 重置到第一页
    },
    // 处理查询（输入时触发，重置页码）
    handleSearch() {
      maintenanceDLBySearch(this.currentPage, this.pageSize, this.searchConfig.lineId, this.searchConfig.machineNumber, this.searchConfig.headNumber).then(response => {
        this.totalCount = response.total;
        this.configList = []
        for (let index = 0; index < response.list.length; index++) {
          const element = response.list[index];
          this.configList.push({
            lineNumber: element.line + "-" + element.side,
            line: element.line,
            side: element.side,
            maintenanceDate: element.maintenanceDate,
            deviceConfigId: element.deviceConfigId,
            machineNumber: element.machineNumber,
            machineHead: element.machineHead,
            headNumber: element.headNumber,
            headCount: element.headCount,
            maintenanceFrequency: element.maintenanceFrequency,
            warningDays: element.warningDays,
            useDay: element.useDay,
            count: element.count,
            maintenanceItem: element.maintenanceItem,
            maintenanceResult: element.maintenanceResult,
            implementer: element.implementer,
            abnormalDescription: element.abnormalDescription
          })
        }
        if (!response.list.length) this.$message({ type: 'error', message: '暂无数据' });
      })
      this.currentPage = 1;
    },
    // 分页：每页条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    // 分页：页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
    },

    // 新增配置：打开弹窗并重置表单
    handleRowDblClick(row) {
      this.dialogTitle = '新增配置';
      this.dialogVisible = true;
      // 重置表单
      this.$nextTick(() => {
        this.$refs.configForm.resetFields();
        this.form = { ...row };
      });
    },
    // 提交表单：新增/编辑保存
    handleSubmit() {
      this.$refs.configForm.validate((isValid) => {
        if (isValid) {
          addMaintenanceLogdata(this.form).then(response => {
            if (response) {
              this.$message({ type: 'success', message: '新增配置成功！' });
              this.handleSearch();
            }
          })
          // 关闭弹窗
          this.dialogVisible = false;
        } else {
          this.$message({ type: 'error', message: '表单验证失败，请检查填写内容！' });
          return false;
        }
      });
    },

    // 表格行点击：可选（增强交互，点击行选中）
    handleRowClick(row) {
      this.$refs.configTable && this.$refs.configTable.setCurrentRow(row);
    }
  }
};
</script>

<style scoped>
/* 保持与原页面一致的样式规范 */
.el-dialog__body {
  padding-bottom: 10px !important;
}

.el-form-item__help {
  color: #606266 !important;
  font-size: 12px !important;
}

.el-table .el-table__cell:focus-within {
  outline: none;
}
</style>